package com.wu.project.admin.api;

import cn.hutool.core.date.format.FastDateFormat;
import com.wu.project.admin.component.JsonResult;
import com.wu.project.admin.entity.AdQueryVO;
import com.wu.project.admin.property.Constants;
import com.wu.project.admin.service.AdvertisingService;
import com.wu.project.admin.util.CommonResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

/**
 * @author 50816
 */
@RestController
public class FileApi {

    Logger logger = LoggerFactory.getLogger(FileApi.class);

    @Autowired
    AdvertisingService advertisingService;

    private final FastDateFormat fastDateFormat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");

    @Value("${app.baseDir}")
    String baseDir;

    @GetMapping("/file")
    public void getFile(String filePath, HttpServletResponse response) {
        if (StringUtils.hasLength(filePath)) {
            File file = new File(baseDir + filePath);
            if (file.exists()) {
                writeFileToResp(file, response);
            } else {
                logger.error("文件不存在:{}", baseDir + filePath);
            }
        } else {
            logger.error("文件路径:{},不存在", baseDir + filePath);
        }
    }

    private void writeFileToResp(File file, HttpServletResponse response) {
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());

        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            byte[] buff = new byte[1024];
            OutputStream os = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            logger.error("读取文件:{}失败,{}", file.getAbsolutePath(), e.getMessage(), e);
        }
    }

    @PostMapping(value = "/uploadList", produces = Constants.APPLICATION_JSON_UTF8)
    public JsonResult uploadFileList(@RequestParam("files") MultipartFile files[], String type) {
        for (MultipartFile file : files) {
            String filename = file.getOriginalFilename();
            String targetFileFullPath = baseDir + File.separator + type + File.separator + filename;
            if (!new File(targetFileFullPath).exists()) {
                new File(targetFileFullPath).mkdirs();
            }
            try {
                file.transferTo(new File(targetFileFullPath));
            } catch (IOException e) {
                logger.error("上传文件{}异常:{}", filename, e.getMessage(), e);
                return CommonResultUtil.Instance.error(filename + "--上传失败");
            }
        }
        return CommonResultUtil.Instance.success();
    }

    @PostMapping(value = "/uploadAd", produces = Constants.APPLICATION_JSON_UTF8)
    public JsonResult uploadFile(@RequestParam("file") MultipartFile file, String type) {
        String filename = file.getOriginalFilename();
        String targetFileFullPath = baseDir + File.separator + type + File.separator + filename;
        if (!new File(targetFileFullPath).exists()) {
            new File(targetFileFullPath).mkdirs();
        }
        try {
            file.transferTo(new File(targetFileFullPath));
            AdQueryVO adQueryVO = new AdQueryVO();
            adQueryVO.setCreateTime(fastDateFormat.format(new Date()));
            adQueryVO.setPath(targetFileFullPath);
            adQueryVO.setState("0");
            return advertisingService.addAd(adQueryVO);
        } catch (IOException e) {
            logger.error("上传文件{}异常:{}", filename, e.getMessage(), e);
            return CommonResultUtil.Instance.error(filename + "--上传失败");
        }
    }
}
